<?php
/**
 * @Name: DepartmentLogic.php
 * @Author: yashuai
 */

namespace App\Http\Logic\Org;

use App\Http\Logic\BaseLogic;
use App\Http\Model\ConstCode;
use App\Http\Model\Org\DepartmentModel;
use App\Http\Model\Org\DepartmentStaffModel;

class DepartmentLogic extends BaseLogic
{

    /**
     * @Desc 添加部门
     * @return bool|int
     * @author yashuai
     */
    public function create()
    {
        return DepartmentModel::newInsert($this->getParamsTableData());
    }

    /**
     * @Desc 编辑部门
     * @return int
     * @throws \App\Exceptions\ApiException
     * @author yashuai
     */
    public function update()
    {
        $info = DepartmentModel::getInfo($this->params['DepartmentID'], 'DepartmentID');
        if (empty($info)) {
            _throw(106001);
        }
        $data = $this->getParamsTableData();
        return DepartmentModel::query()->where(['DepartmentID' => $this->params['DepartmentID']])->update($data);
    }

    /**
     * @Desc 删除部门
     * @return int
     * @throws \App\Exceptions\ApiException
     * @author yashuai
     */
    public function delete()
    {
        $info = DepartmentModel::getInfo($this->params['DepartmentID'], 'DepartmentID');
        if (empty($info)) {
            _throw(106001);
        }
        if ($info['Status'] == ConstCode::BASIC_STATUS_DELETE) {
            return 0;
        }
        // todo 部门下有员工，禁止删除
        // ...
        return DepartmentModel::query()->where(['DepartmentID' => $this->params['DepartmentID']])->update([
            'Status' => ConstCode::BASIC_STATUS_DELETE,
        ]);
    }

    /**
     * @Desc 更新部门人数
     * @method
     * @author yashuai
     */
    public function updatePeopleNum()
    {
        // todo 更新部门人数   $this->params['DepartmentID']
    }

    /**
     * @Desc 数据转为表结构数据
     * @return array
     * @author yashuai
     */
    private function getParamsTableData()
    {
        return [
            'Name'     => $this->params['Name'],
            'ParentID' => _array_field($this->params, 'ParentID', 0),
            'Order'    => _array_field($this->params, 'Order', 0),
            'MasterID' => _array_field($this->params, 'MasterID', 0),
            'Status'   => _array_field($this->params, 'Status', ConstCode::BASIC_STATUS_NORMAL)
        ];
    }

}
